package com.interviewbackend.util;

import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
import com.alibaba.dashscope.audio.tts.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.tts.SpeechSynthesisAudioFormat;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Base64;

@Component
public class SpeechSynthesisUtil {

    // 通过 @Value 注解读取配置文件中的 API Key
    @Value("${dashscope.api.key}") // 修改成你实际在配置文件中的 API Key 属性名
    private String apiKey;

    public String synthesizeToBase64(String text, String style) {
        if(style == null) style = "sambert-zhimiao-emo-v1";
        SpeechSynthesizer synthesizer = new SpeechSynthesizer();
        SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .model(style)
                .text(text)
                .sampleRate(48000)
                .format(SpeechSynthesisAudioFormat.WAV)
                .apiKey(apiKey)
                .build();

        // 同步获取合成结果
        ByteBuffer audio = synthesizer.call(param);

        // 将字节数组转换为 Base64 编码的字符串
        return Base64.getEncoder().encodeToString(audio.array());
    }
}

